package com.benmei.weike.service;

import com.benmei.weike.common.Constants;
import com.benmei.weike.dao.StudentDao;
import com.benmei.weike.dto.otherplatform.LoginDto;
import com.benmei.weike.entity.Student;
import com.benmei.weike.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Peter on 2018/4/14.
 */
@Component
public class StudentService {

    @Autowired
    private StudentDao studentDao;

    // 第三方平台的注册或登录
    public Student loginOrRegiest(LoginDto loginDto) {
        String uid = loginDto.getUid();
        Student student = studentDao.getByIncourseUid(uid);
        // 用户不存在，新注册
        if (student == null) {
            student = new Student();
            student.setToken(UUID.randomUUID().toString());
            student.setIncourse_uid(uid);
            student.setMemb_name(uid);
            Date now = new Date();
            String yearMonth = DateUtil.format(now, "yyyyMM");
            student.setMemb_register_time(now);
            student.setMemb_register_month(yearMonth);
            student.setTotal_study_times(0);
            student.setMemb_balance(new BigDecimal(0));
            student.setMemb_phone_area(loginDto.getPhone_area());
            student.setMemb_phone(loginDto.getPhone());
            student.setMemb_islock(Constants.Member.IsLock.unLocked);//0锁定1未锁定  只有为1时才能登陆
            student.setUid(UUID.randomUUID().toString());
            student.setMemb_head_portrait("http://file.waijiaojun.com/waijiaojun/app/image/head_InCourse.png");
            studentDao.insertSelective(student);
        } else {
            // 更新或添加电话号码
            if (StringUtils.isNotBlank(loginDto.getPhone())) {
                student.setMemb_phone(loginDto.getPhone());
                student.setMemb_phone_area(loginDto.getPhone_area());
                studentDao.update(student);
            }
        }
        return student;
    }
}
